import { app, ipcMain, session, BrowserWindow, type Cookie } from 'electron';
import { awaitFind, getAppName } from './utils';
let top: BrowserWindow;

const setTopBrowserWindow = (t: BrowserWindow) => {
    top = t;
}
const parseCookie = (cookies: Cookie[]) => {
    let obj: { [key: string]: any } = {};
    cookies.forEach((item) => {
        obj[item.name] = item.value;
    });
    return obj;
}
ipcMain.on('exe', (e) => {
    const p = app.getPath('exe');

    e.sender.send('exe', p);
});
ipcMain.on("sid", async (e, args?: { username: string, password: string }) => {
    const cookies = await session.defaultSession.cookies.get({});
    cookies.forEach((cookie) => {
        let url = '';
        url += cookie.secure ? 'https://' : 'http://';
        url += cookie.domain!.charAt(0) === '.' ? 'www' : '';
        url += cookie.domain;
        url += cookie.path;
        session.defaultSession.cookies.remove(url, cookie.name);
    });

    const win = new BrowserWindow({
        show: false,
        maximizable: false,
        resizable: false,
        minimizable: false,
        width: 400,
        height: 400,
        parent: top,
        modal: true,
        movable: false,
        title: getAppName(),
        webPreferences: {
            nodeIntegration: true,
            contextIsolation: false,
            webviewTag: true,
            webSecurity: false
        },
    });
    win.show();
    win.setMenu(null);
    win.loadURL("https://login.taobao.com/member/login.jhtml?sub=true&style=miniall&newMini2=true&full_redirect=true&css_style=we&minipara=1,1,1&redirectURL=http%3A%2F%2Fwe.taobao.com");
    if (args?.username && args.password) {
        // @ts-ignore (define in dts)
        awaitFind(async () => {
            const result = await win.webContents.executeJavaScript(`
                    Object.defineProperty(navigator, 'webdriver', { get: () => undefined });
                    Object.defineProperty(navigator, 'plugins', { get: () => [] });
                    Object.defineProperty(navigator, 'languages', { get: () => ["zh-CN", "zh"] });
                    function __run(){
                        var username = document.getElementById('fm-login-id');
                        var password = document.getElementById('fm-login-password');
                        function __input(input,value,index,cb){
                            input.value += value[index];
                            index++;
                            if(index<value.length){
                                setTimeout(function(){
                                    __input(input,value,index,cb);
                                },10);
                            }else{
                                cb();
                            }
                        }
                        if(username){
                            __input(username,"${args.username}",0,function(){
                                __input(password,"${args.password}",0,function(){
                                    setTimeout(function(){
                                        document.querySelector('.password-login').click();
                                    },1000);
                                });
        
                            });
                           
                            return  true;
                        }
                    }
                    __run();
                `, true);
            if (result) {
                return false;
            }

        });

        // @ts-ignore (define in dts)
        awaitFind(async () => {
            if (win.isDestroyed()) {
                return false;
            }
            const result = await win.webContents.executeJavaScript(`
               function __runOtherValidator(){
                var iframe = document.querySelector('.login-check-static');
                if(iframe){
                    iframe =  iframe.children[0]
                    const idocument = iframe.contentWindow.document;
                    if(idocument.querySelector('#otherValidator')){
                        idocument.querySelector('#otherValidator').click();
                        return true;
                    }
                }
                    
               }

               __runOtherValidator();
            
            `, true);

            if (result) {
                return false;

            }
        });


        // @ts-ignore (define in dts)
        awaitFind(async () => {
            if (win.isDestroyed()) {
                return false;
            }
            const result = await win.webContents.executeJavaScript(`
               function __runOtherValidatorSend(){
                var iframe = document.querySelector('.login-check-static');
                if(iframe){
                    iframe =  iframe.children[0]
                    const idocument = iframe.contentWindow.document;
                    if(idocument.querySelector('.ui-button.ui-button-small')){
                        idocument.querySelector('.ui-button.ui-button-small').click();
                        return true;
                    }
                }
                    
               }

               __runOtherValidatorSend();
            
            `, true);

            if (result) {
                return false;

            }
        });

    }





    // @ts-ignore (define in dts)
    awaitFind(async () => {
        if (win.isDestroyed()) {
            return false;
        }
        const cookies = await win.webContents.session.cookies.get({});
        const obj = parseCookie(cookies);
        if (obj['cookie2'] && obj['login']) {
            return {
                sid: obj['cookie2'],
                nick: decodeURIComponent(obj['tracknick']).replace(/\\u/g, '%u'),
                uid: obj['unb']
            }
        }

    }).then((info) => {
        if (info) {
            win.close();
            e.sender.send('sid', info);
        }
    });


});

export { setTopBrowserWindow };